package kokonut.admin;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import java.io.IOException;
import java.util.ArrayList;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kokonut.shop.color.Color;
import kokonut.shop.product.Image;
import kokonut.shop.product.TShirtModel;
import kokonut.shop.size.Size;
import persistence.PMF;
import persistence.ProductPersistence;
import utils.ProductEditor;

public class EditProductServlet extends HttpServlet {

    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String productName = req.getParameter("name");
        int ref = Integer.parseInt(req.getParameter("ref"));
        String type = req.getParameter("type");
        String imageURL = req.getParameter("imageURL");
        if (type.equals("T-Shirt")) {
            //TODO JavaScript bidez seguru egon tallarenbat gutxienez aukeratu dala
            String[] sizes = req.getParameterValues("sizes");
            ArrayList<Size> availableSizes = ProductEditor.createSizes(sizes);
            availableSizes = ProductEditor.assignPriceToSizes(availableSizes, req);
            String[] colors = req.getParameterValues("colors");
            ArrayList<Color> availableColors = ProductEditor.createColors(colors);
            ArrayList<Image> images = ProductEditor.assignImages(req, availableColors);
            TShirtModel shirt = new TShirtModel(ref, productName, availableSizes, availableColors, images);

            PersistenceManager pm = PMF.get().getPersistenceManager();

            ProductPersistence persistence = new ProductPersistence();
            persistence.deleteProductByRef(ref);
            persistence.saveModel(shirt);
            persistence.closePM();
        }
        resp.sendRedirect("/admin/shopAdmin");
    }

    
}
